import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.concurrent.CountDownLatch;

/**
 * Created by khiker on 2016/8/2.
 */
@Slf4j
@SpringBootApplication//启用自动配置
@ComponentScan(basePackages = "com.zkaler.dubbo",useDefaultFilters = false,includeFilters ={@ComponentScan.Filter( value = {Service.class})})
@EnableTransactionManagement
@ImportResource("classpath:dubbo-provider.xml")
@PropertySource(value = "classpath:dubbo.properties", ignoreResourceNotFound = true)
public class SpringBootJdbcApplication {
    public static void main(String[] args) throws InterruptedException {
        log.info("开始启动dubbo");
        System.setProperty("dubbo.application.logger", "slf4j");
//        SpringApplication.run(SpringBootJdbcApplication.class, args);
        ApplicationContext ctx = new SpringApplicationBuilder()
                .sources(SpringBootJdbcApplication.class)
                .web(false) // 没错，把项目设置成非web环境
                .run(args);
        log.info("dubbo启动成功!");
        CountDownLatch closeLatch = new CountDownLatch(1);
        closeLatch.await();
    }

    @Autowired
    private Environment env;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名
        dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class"));//数据方言
        dataSource.setInitialSize(5);
        dataSource.setMaxActive(100);
        dataSource.setMinIdle(5);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        return dataSource;
    }
}
